package registration;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.swing.JFileChooser;

import client.WelcomePanelDescriptor;

import certificate.X509CertificateHandler;

import wizard.Wizard;
import wizard.WizardPanelDescriptor;

public class PersonalDataPanelDescriptor extends WizardPanelDescriptor implements ActionListener{

    public static final String IDENTIFIER = "PERSONAL_DATA_PANEL";
    private PersonalDataPanel pdp;
    private PersonalData data;
    
    public PersonalDataPanelDescriptor() {
    	pdp = new PersonalDataPanel();
    	pdp.addGenerateButtonActionListener(this);
    	
    	setPanelDescriptorIdentifier(IDENTIFIER);
    	setPanelComponent(pdp);
    }
    
    public String getNextPanelDescriptor() {
        return RegistrationCompletePanelDescriptor.IDENTIFIER;
    }
    
    public String getBackPanelDescriptor() {
        return WelcomePanelDescriptor.IDENTIFIER;
    }
    
    public void generateKeys(){
        SecureRandom random;
        File keyStoreFile = null;
        KeyPairGenerator keyGen;
        
        String dnString = pdp.getDataForCert();
        System.out.println(dnString);
        data = pdp.getDataForServer();
        
        
        try{
        	keyGen = KeyPairGenerator.getInstance("RSA");
        	random = SecureRandom.getInstance("SHA1PRNG");
            keyGen.initialize(2048, random);
            KeyPair pair = keyGen.generateKeyPair();
            X509Certificate cert = X509CertificateHandler.generate(dnString, pair, "SHA1withRSA", 30);
            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("Save Keys");
            int returnVal = chooser.showSaveDialog(getWizard().getDialog());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                keyStoreFile = chooser.getSelectedFile();
                if (!keyStoreFile.getPath().isEmpty()) {
                	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                	ks.load(null, data.getsecretCode().toCharArray());
                	Certificate[] certChain = {cert};
                	// we save a keystore object with a pesel as an identifier string and
                	// secret code as a password
            		ks.setKeyEntry(data.getpesel(),pair.getPrivate(),data.getsecretCode().toCharArray(),certChain);
            		FileOutputStream foStream = new FileOutputStream(keyStoreFile);
            		ks.store(foStream,data.getsecretCode().toCharArray());
            		
            		// store the path to the keyStore in wizard
            		getWizard().storePanelData(IDENTIFIER+"keyStorePath", keyStoreFile.getAbsolutePath());
            		getWizard().setNextFinishButtonEnabled(true);
                }
            }
        }
        catch(IOException e){
        	System.out.println("Cannot write to file.");
        	e.printStackTrace();
        	getWizard().close(Wizard.ERROR_RETURN_CODE);
        }
        catch(NoSuchAlgorithmException e){
        	e.printStackTrace();
        	getWizard().close(Wizard.ERROR_RETURN_CODE);
        }
        catch (Exception e) {
            e.printStackTrace();
            getWizard().close(Wizard.ERROR_RETURN_CODE);
        }
    }
    
    @Override
    public void aboutToDisplayPanel(){
    	getWizard().setNextFinishButtonEnabled(false);
    }
    
    @Override
    public void aboutToHidePanel(){
    	getWizard().storePanelData(IDENTIFIER+"PersonalData", data);
    	
    	System.out.println("PersonalData stored in the wizard.");
    }

	@Override
	public void actionPerformed(ActionEvent arg0) {
			generateKeys();
	}
}
